package com.zzb.codegenerator.generator.dctm.hive;

import com.zzb.codegenerator.bean.TableColumn;
import com.zzb.codegenerator.bean.TableMeta;
import com.zzb.codegenerator.config.GeneratorConfig;
import com.zzb.codegenerator.generator.connect.ConnectPool;
import com.zzb.codegenerator.generator.context.TableMetaContext;
import com.zzb.codegenerator.generator.dctm.DbToTableMetaConvertor;
import com.zzb.codegenerator.generator.table.ITableMetaFoctory;
import com.zzb.codegenerator.utils.GetJdbcUrlUtil;
import com.zzb.codegenerator.utils.HiveTypeToJavaType;
import com.zzb.codegenerator.utils.OperatorEnvUtils;
import com.zzb.codegenerator.utils.SQLServerTypeToJavaType;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zhangzhenbin on 18-4-9.
 */
public class HiveToTableMetaConvertor implements DbToTableMetaConvertor {
    private static final String hiveTableMetaSQL = "DESCRIBE {tableName}";
    private GeneratorConfig generatorConfig;

    public HiveToTableMetaConvertor(GeneratorConfig generatorConfig) {
        this.generatorConfig = generatorConfig;
    }

    @Override
    public TableMeta convertFromTableName(String tableName) throws Exception {
        TableMeta tableMeta = new TableMeta();
        tableMeta.setTableName(tableName);
        List<TableColumn> list = new ArrayList<>();

        //获取连接
        Connection connection = ConnectPool.getConnection(GetJdbcUrlUtil.getDriverName(generatorConfig.getJdbcUrl()),
                generatorConfig.getJdbcUrl(), generatorConfig.getJdbcUsername(), generatorConfig.getJdbcPassword());
        if (connection == null) throw new Exception("数据库连接失败");
        if (!tableExist(connection, tableName)) return null;
        String sql = hiveTableMetaSQL.replace("{tableName}", tableName);
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        tableMeta.setPrimaryKeyColumns(new ArrayList<>());
        while (rs.next()) {
            TableColumn tableColumn = new TableColumn();
            tableColumn.setColumnName(rs.getString("name"));
            tableColumn.setColumnType(rs.getString("type"));
            tableColumn.setMaxLength(0L);
            tableColumn.setPrecision(0L);
            tableColumn.setScale(0L);
            tableColumn.setNullable(rs.getBoolean("nullable"));
            tableColumn.setUnsigned(false);
            tableColumn.setDefaultValue(rs.getString("default_value"));
            tableColumn.setPrimaryKey(rs.getBoolean("primary_key"));
            tableColumn.setColumnComment(rs.getString("comment"));
            tableColumn.setColumnTypeFullName(rs.getString("type"));
            try {
                tableColumn.setPropertyType(HiveTypeToJavaType.hive2Java.get(tableColumn.getColumnType()).getJavaType());
                tableColumn.setPropertyFullType(HiveTypeToJavaType.hive2Java.get(tableColumn.getColumnType()).getJavaFullType());
                tableColumn.setJdbcType(HiveTypeToJavaType.hive2Java.get(tableColumn.getColumnType()).getSqlserverType().getName());
            } catch (Exception e) {
                System.out.println("类型转换异常！[{name}]-[{type}]"
                        .replace("{name}", tableColumn.getColumnName())
                        .replace("{type}", tableColumn.getColumnType()));
            }
            tableColumn.setPropertyName(ITableMetaFoctory.rename(generatorConfig.getNameType(), tableColumn.getColumnName()));
            if (tableColumn.getPrimaryKey()) {
                tableMeta.getPrimaryKeyColumns().add(tableColumn);
            }
            list.add(tableColumn);
        }
        tableMeta.setTableColumns(list);
        tableMeta.setConfig(generatorConfig);
        tableMeta.setTableName(tableName);
        tableMeta.setBeanName(TableMetaContext.getTableMap().get(tableName));
        tableMeta.setTableComment("");
        tableMeta.setSystemUserName(OperatorEnvUtils.getSystemUserName());
        tableMeta.setCurrentTime(new Date());
        return tableMeta;
    }

    @Override
    public boolean tableExist(Connection connection, String tableName) {
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select 1 from `" + tableName + "`");
            resultSet.next();
            resultSet.close();
            statement.close();
            return true;
        } catch (SQLException e) {
            return false;
        }
    }
}
